/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package javalee.util;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.table.TableModel;

/**
 *
 * @author lucajr
 */
public class ExportaCSV {
    
    JFileChooser fc = new JFileChooser();
    
    public ExportaCSV() { }
    public void exportTable(JTable table, String defaultFileName) throws IOException {
        
            fc.setDialogTitle("Escolha o arquivo para exportar");
            fc.setApproveButtonText("Exportar!");
            fc.setFileFilter(new FileNameExtensionFilter(defaultFileName, "*.xls"));
            
            if(fc.showSaveDialog(null) == JFileChooser.APPROVE_OPTION){
                        File file = fc.getSelectedFile();

                        TableModel model = table.getModel();
                        FileWriter out = new FileWriter(file);
                        for(int i=0; i < model.getColumnCount(); i++) {
                out.write(model.getColumnName(i) + "\t");
                        }
                        out.write("\n");

                        for(int i=0; i< model.getRowCount()-1; i++) {
                for(int j=0; j < model.getColumnCount(); j++) {
                        out.write(model.getValueAt(i,j).toString()+"\t");
                        System.out.println(model.getValueAt(i,j).toString());
                        }
                        out.write("\n");
                }

                out.close();
                System.out.println("write out to: " + file);

            }
            
    }
}
